/*
 * @(#)UserContentListener.java 0.0.1-SNAPSHOT
 *
 * Copyright Group B
 */

package grupb.upf.ms.listeners;

import grupb.upf.XMLObjects.Photo;
import grupb.upf.DBManager.DBAction;
import grupb.upf.DBManager.DBActionResult;
import grupb.upf.DBManager.DBManager;
import grupb.upf.XMLObjects.Video;
import grupb.upf.ms.Content;
import grupb.upf.ms.DescriptionContent;
import grupb.upf.ms.UserContent;
import java.io.File;
import java.util.List;
import javax.swing.ImageIcon;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.muc.MultiUserChat;

/**
 * <p>This component implements a PacketListener Interface. It receives
 * the content.</p>
 *
 * @version    0.0.1-SNAPSHOT
 * @author     Group B
 */
public final class UserContentListener implements
        org.jivesoftware.smack.PacketListener {

    /**
     * The logger. A new logger <code>grupb.upf.ms.UserContentListener</code>
     * is created to add the logs of this class.
     */
    private static final Log LOG =
            LogFactory.getLog(UserContentListener.class);
    /**
     * The channel to listen to.
     */
    private MultiUserChat chat = null;
    /**
     * This method load the properties for the chat.
     * @param ch The chat
     */
    public UserContentListener(final MultiUserChat ch) {
        this.chat = ch;
    }
/**
 * Listens an passes to the inferace the chat messages.
 * @param packet The message
 */
    @Override
    public void processPacket(final Packet packet) {
        // Put the incoming message on the chat history or chat board.
        final Message msg = (Message) packet;
        if (LOG.isInfoEnabled()) {
            final StringBuffer sb =
                    new StringBuffer(msg.getPacketID())
                    .append(" received from ").append(msg.getFrom());
            LOG.info(sb);
        }
        final UserContent uc =
                (UserContent) msg.getProperty("UserContent");
        Object [] params = new Object[1];
        String key = "";
        int index = uc.getURL().indexOf(":");
        String ip = "";
        String url = "";
        if (index != -1) {
            ip = uc.getURL().substring(index + 1);
            url = uc.getURL().substring(0, index);
        } else {
            url = uc.getURL();
        }
        params[0] = url;
        final String ext = url.substring(url.lastIndexOf("."));
        if (index == -1) {
                key = "query.photo.url";
        } else {
            key = "query.video.url";
        }
        //Creamos la nueva action
        final DBAction dba = new grupb.upf.DBManager.impl.DBAction(key, params);
        //Pedimos una instancia para hacer la query
        final DBManager dbm = grupb.upf.DBManager.impl.DBManager.getInstance();
        final DBActionResult actionResult = dbm.execute(dba);
        //Ahora mostramos los resultados
        //Tenemos que hacerlo bien...
        final List res = actionResult.getResult();
        Content c;
        DescriptionContent dc;
        Object obj = null;
        for (int i = 0; i < res.size(); i++) {
            dc = new grupb.upf.ms.impl.DescriptionContent();
            if (res.get(i) instanceof Photo) {
                StringBuffer sb = new StringBuffer(
                        grupb.upf.util.Config.getProperty("photo.folder"))
                        .append(((Photo) res.get(i)).getURL());
                url = sb.toString();
                obj = new ImageIcon(url);
                dc.addProperty("properties", (Photo) res.get(i));
            c = new grupb.upf.ms.impl.Content(obj, dc);
            sendContent(c, msg.getFrom());
            } else if (res.get(i) instanceof Video) {
                //Enviamos a reproducir, tenemos la IP y el archivo
                if (grupb.upf.util.Config.getProperty("vlc.folder") != null
                        && grupb.upf.util.Config.getProperty(
                                "ip") != null) {
                    Video v = (Video) res.get(i);
                    //Enviamos
                    final File f = new File(grupb.upf.util
                        .Config.getProperty("vlc.folder"));
                    final File f2 = new File(grupb.upf.util.Config
                            .getProperty("video.folder"));
                    if (LOG.isInfoEnabled()) {
                        LOG.info("Reproducing the video");
                    }
                    try {
                        Process a = Runtime.getRuntime().exec("\""
                                + f.getAbsolutePath()
                                + "\\vlc\" -vvv " + f2.getAbsolutePath() + "\\"
                                + v.getURL().replaceAll("/", "\\\\")
                                + " --sout udp://" + ip + ":1234 --ttl 12");
                    } catch (Exception err) {
                        if (LOG.isFatalEnabled()) {
                            LOG.fatal("Fatal error reproducing the video.",
                                    err);
                        }
                    }
                } else {
                    if (LOG.isErrorEnabled()) {
                        LOG.error("Someone wanted to reproduce a video, but this user haven't the VLC configured.");
                    }
                }

            }
        }
    }
   /**
    * This method is in charge to answer the searchProfile messages received.
    * @param content The search to send
    * @param to The destination
    */
    private void sendContent(final Content content, final String to) {
        Message msg = new Message();
        StringBuffer sb =
                new StringBuffer("Content is being sent to user: ");
        sb.append(to);
        LOG.info(sb);
        sb = new StringBuffer(to);
        sb.append("/Home");
        msg.setTo(sb.toString());
        msg.setPacketID("Content");
        msg.setProperty("Content", (Object) content);
        try {
            chat.sendMessage(msg);
        } catch (XMPPException ex) {
            LOG.fatal("Error sending message", ex);
            //p2p.addInfo("Fatal error sending message");
        }
    }
}
